package com.huodongrili.calender.data;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.huodongrili.calender.model.Comment;

public class CommentData {

	private Context mContext;

	public CommentData(Context context) {
		mContext = context.getApplicationContext();
	}
	
	
	public long addComment(String eid,boolean like,long date){
		long backCode = -1;
		SQLiteDatabase db = DBHelper.getWriteDatabase(mContext);
		
		int likes = like==true? 1:0;
		
		ContentValues cv = new ContentValues();
		cv.put(com.huodongrili.calender.data.DBTables.Comment.E_ID, eid);
		cv.put(com.huodongrili.calender.data.DBTables.Comment.DATELONG, date);
		cv.put(com.huodongrili.calender.data.DBTables.Comment.LIKE, likes);
		
		backCode = db.insert(com.huodongrili.calender.data.DBTables.Comment.TABLE_NAME, null, cv);
		
		return backCode;
	}
	
	
	public void clearComments(){
		SQLiteDatabase db = DBHelper.getWriteDatabase(mContext);
		
		String sql = "delete from " + com.huodongrili.calender.data.DBTables.Comment.TABLE_NAME;
		db.execSQL(sql);
		
	}
	
	

	public List<Comment> getComments() {

		SQLiteDatabase db = DBHelper.getReadDatabase(mContext);

		Cursor cursor = null;
		List<Comment> comments = null;

		try {

			cursor = db.rawQuery("select * from " + com.huodongrili.calender.data.DBTables.Comment.TABLE_NAME, null);
			int count = cursor.getCount();
			if (cursor != null && count > 0) {
				comments = new ArrayList<Comment>(count);
				cursor.moveToFirst();
				while (!cursor.isAfterLast()) {
					String eid = cursor.getString(cursor
							.getColumnIndex(com.huodongrili.calender.data.DBTables.Comment.E_ID));
					long date= cursor.getLong(cursor
							.getColumnIndex(com.huodongrili.calender.data.DBTables.Comment.DATELONG));
					int check = cursor.getInt(cursor
							.getColumnIndex(com.huodongrili.calender.data.DBTables.Comment.CHECKED));
					int like = cursor.getInt(cursor
							.getColumnIndex(com.huodongrili.calender.data.DBTables.Comment.LIKE));

					boolean likes = like == 1 ? true : false;
					
					Comment comm = new Comment();
					comm.setChecked(check);
					comm.setDateLong(date);
					comm.seteId(eid);
					comm.setLike(likes);
					
					comments.add(comm);
					
					cursor.moveToNext();
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (cursor != null) {
				cursor.close();
			}
		}
		
		return comments;

	}

}
